//
//  RTComposeViewController.swift
//  Weibo
//
//  Created by Brisinga on 16/3/13.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit

class RTComposeViewController: UIViewController {
    
    
    // 记录是否进行动画
    private var doAnimation: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    
    @objc private func keyboardDidChangeFrame(notify: NSNotification) {
        
        print(notify)
        
        if doAnimation == false {
        
            return
        }
        
        
        let endFrame = (notify.userInfo![UIKeyboardFrameEndUserInfoKey]! as! NSValue).CGRectValue()
        
        let duration = (notify.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as! NSNumber).doubleValue
        
        // 更新约束
        composeToolBar.snp_updateConstraints{ (make) -> Void in
            
            make.bottom.equalTo(endFrame.origin.y - kScreenHeight)
        }
        
        
        // 更新
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.composeToolBar.layoutIfNeeded()
        }
    }
    
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 返回
    @objc private func backAction() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    // 选择图片
    private func pickPhoto() {
    
        print("选择图片")
        
        let picVC = UIImagePickerController()
        
        picVC.delegate = self
        
        presentViewController(picVC, animated: true, completion: nil)
    }
    
    // 切换键盘
    private func switchKeyboard() {
    
        if textView.inputView == nil {
            
            textView.inputView = emotionKeyboard
            
            composeToolBar.isSystemKeyboard = false
            
        }else {
        
            textView.inputView = nil
            
            composeToolBar.isSystemKeyboard = true
        }
        
        doAnimation = false
        textView.resignFirstResponder()
        
        
        doAnimation = true
        textView.becomeFirstResponder()
    }
    
    
    
    // 懒加载控件
    
    
    // enmotionKeyboard
    private lazy var emotionKeyboard: RTEmotionKeyboard = {
    
        let emotionKeyboard = RTEmotionKeyboard()
        
        emotionKeyboard.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 216)
        
        return emotionKeyboard
    }()
    
    
    
    //pictureView
    private lazy var pictureView: RTComposeCollectionView = {
    
        let pictureView = RTComposeCollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())

    
        pictureView.composeCollectionCourse = {[weak self] (collection: RTComposeCollectionView) in
            
            self?.pickPhoto()
        }
        
        return pictureView
    }()
    
    
    // stackview
    private lazy var composeToolBar: RTComposeToolBar = {
        
        let composeToolBar = RTComposeToolBar(frame: CGRectZero)
        
        composeToolBar.composeToolBarButtonCallBack = {[weak self] (type:RTComposeToolBarButtonType) in
            
            switch type {
            
            case .Picture:
                print("图片")
                self?.pickPhoto()
    
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("emoticon")
                self?.switchKeyboard()
            case .Add:
                print("加号")
            
            }
        
        }
        
        return composeToolBar
    }()
    
    
    private lazy var titleLabel: UILabel = {
        
        let titleLable = UILabel()
        
        titleLable.numberOfLines = 0
        
        titleLable.textAlignment = .Center
        
        // 设置文字信息
        let infoDict = [
            
            NSForegroundColorAttributeName: UIColor.lightGrayColor(),
            NSFontAttributeName: UIFont.systemFontOfSize(14),
            NSStrokeColorAttributeName: UIColor.redColor(),
            NSStrokeWidthAttributeName: 5
            
        ]
        
        // 获取用户昵称
        if let screenName = RTUserAcountViewModel.sharedAccountViewModel.acount?.screen_name {
            
            // 设置标题
            let text = "发微博\n\(screenName)"
            
            let attributeText = NSMutableAttributedString(string: text)
            
            let range = (text as NSString).rangeOfString(screenName)
            
            attributeText.addAttributes(infoDict, range: range)
            
            titleLable.attributedText = attributeText
            
        } else {
            
            titleLable.text = "转发微博"
        }
        
        
        titleLable.sizeToFit()
        
        return titleLable
    }()
    
    
    
    // 发送按钮
    private lazy var rightBtn: UIButton = {
        
        let rightBtn = UIButton()
        
        rightBtn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        rightBtn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        rightBtn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        
        rightBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        rightBtn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Disabled)
        
        rightBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        rightBtn.setTitle("发送", forState: UIControlState.Normal)
        
        rightBtn.bounds.size = CGSize(width: 40, height: 34)
        
        return rightBtn
    }()
    
    // textView
    private lazy var textView: RTTextView = {
    
        let textView = RTTextView(frame: CGRectZero, textContainer: nil)
        
        textView.font = UIFont.systemFontOfSize(16)
        
        textView.placeholder = "世界还小,我陪你去到天涯海角,一次就好,我带你去看天荒地老"
        
        textView.delegate = self
        
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
}

extension RTComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        textView.resignFirstResponder()
    }
}


extension RTComposeViewController: UINavigationControllerDelegate,UIImagePickerControllerDelegate {


    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scaleToWidth(600)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        self.pictureView.addImage(scaleImage)
        
    }
    
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
        print("取消点击了")
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}


extension RTComposeViewController {

    // 初始化内部组件
    private func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNavgationItem()
        
        
        // 设置textView
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.view)
        }
        
        
        // 设置stackView
        view.addSubview(composeToolBar)
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.bottom.trailing.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        // 设置pictureView
        textView.addSubview(pictureView)
        
        pictureView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(100)
            make.leading.equalTo(10)
            make.width.equalTo(self.textView.snp_width).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    private func setupNavgationItem() {
        
        // 设置返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "backAction")
        
        // 设置titleLabel
        navigationItem.titleView = titleLabel
        
        // 设置右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        navigationItem.rightBarButtonItem?.enabled = false
        
    }


}